package com.jfinalnat.httpclient.sdk;

import org.apache.http.HttpHost;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

public class HttpClientFactory {

	private static CloseableHttpClient httpClient;
	
	public static CloseableHttpClient getHttpClient () {
		
		if (!PoolingHttpClientConfig.isEnableConnectionManager) {
			
			return HttpClients.custom().addInterceptorLast(new HttpCrossIntercepter()).setRetryHandler(new MyHttpRequestRetryHandler()).build();
		}
		
		if (httpClient == null) {
			
			PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
			// Increase max total connection to 200
			cm.setMaxTotal(PoolingHttpClientConfig.maxTotal);
			// Increase default max connection per route to 20
			cm.setDefaultMaxPerRoute(PoolingHttpClientConfig.defaultMaxPerRoute);
			// Increase max connections for localhost:80 to 50
			HttpHost localhost = new HttpHost("locahost", PoolingHttpClientConfig.localhostRoutePort);
			cm.setMaxPerRoute(new HttpRoute(localhost), PoolingHttpClientConfig.maxPerRoute);
			
			//定时清除已关闭的连接
			new IdleConnectionMonitorThread(cm).start();
			
			httpClient = HttpClients.custom().addInterceptorLast(new HttpCrossIntercepter()).setRetryHandler(new MyHttpRequestRetryHandler()).setConnectionManager(cm).build();
		}

		return httpClient;
	}
	
}
